package sg4c.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;

public class TextInputProtocol implements DataInputProtocol {

    private final InputStream is;
    private StringTokenizer tokenizer=null;

    public TextInputProtocol(InputStream is) {
        this.is = is;
    }

    public void next() throws IOException {
        StringBuilder builder = new StringBuilder();
        int bufch;
        while( (bufch=is.read())!=-1 ){
            if(bufch=='\n') break;
            else{
                builder.append((char)bufch);
            }
        }
        
        tokenizer = new StringTokenizer(builder.toString(), "\t");
    }

    public int readInt() throws IOException {
        String token = tokenizer.nextToken();
        return (int) Long.parseLong(token, 16);
    }

    public float readFloat() throws IOException {
        String token = tokenizer.nextToken();
        return Float.parseFloat(token);
    }

    public double readDouble() throws IOException {
        String token = tokenizer.nextToken();
        return Double.parseDouble(token);
    }

    public String readString() throws IOException {
        final int len = readInt();
        String str = tokenizer.nextToken();
        if( str.length() != len ){
            throw new IOException("string length mismatch");
        }
        return str;
    }
}
